<?php
	class Utils {

		public static function clearedHTML($string) {
			$string = htmlspecialchars_decode(trim($string));
			$string = strtr($string, array(
				'&frasl;' => '/',
			));

			return $string;
		}

		public static function parseFloat($string) {
			return doubleval(strtr(trim($string), array(
				'руб / шт.' => '',
				' '         => '',
				','         => '.',
				'р'         => '',
			)));
		}

		public static function escapeFile($filename) {
			if (strpos($filename, '..') !== false) return '';

			return $filename;
		}

		public static function delDir($dir) {
			$files = array_diff(scandir($dir), array('.', '..'));
			foreach ($files as $file) {
				(is_dir("$dir/$file")) ? self::delDir("$dir/$file") : unlink("$dir/$file");
			}

			return rmdir($dir);
		}

		public static function createXLS($data, $filename, $title, $header = false) {

			if (file_exists($filename . '_proc.xls'))
				unlink($filename . '_proc.xls');

			$objPHPExcel = new PHPExcel();
			$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory;
			PHPExcel_Settings::setCacheStorageMethod($cacheMethod);

			$locale      = 'ru_ru';
			$validLocale = PHPExcel_Settings::setLocale($locale);
			if (!$validLocale) {
				echo 'Unable to set locale to ' . $locale . " - reverting to en_us<br />\n";
			}


			$objPHPExcel->setActiveSheetIndex(0);
			$worksheet = $objPHPExcel->getActiveSheet();
			$worksheet->setTitle($title);

			$row_num = 1;

			foreach ($data as $row) {
				if ($header && $row_num == 1) {
					$col_num = 0;
					foreach (array_keys($row) as $column) {
						$worksheet->setCellValueByColumnAndRow($col_num, $row_num, $column, true);
						$worksheet->getStyleByColumnAndRow($col_num, $row_num)->applyFromArray(array(
							'font' => array(
								'name' => 'Arial Cyr',
								'size' => '10',
								'bold' => true
							)
						));
						$worksheet->getColumnDimensionByColumn($col_num)->setAutoSize(true);
						$col_num++;
					}
					$row_num++;
				}
				$col_num = 0;

				foreach ($row as $column) {

					$worksheet->setCellValueByColumnAndRow($col_num, $row_num, $column, true);
					$col_num++;
				}
				$row_num++;
			}


			$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
			$objWriter->save($filename . '_proc.xls');

			if (file_exists($filename . '.xls'))
				unlink($filename . '.xls');

			rename($filename . '_proc.xls', $filename . '.xls');
		}

		public static function passGen($min_chars = 8, $max_chars = 10) {
			$chars = "ABCDEFGHJKLMNPRSTWXYZ23456789abcdefghijkmnpqrstwxyz";

			$escape_char_plus = 0;
			$repeat           = mt_rand($min_chars, $max_chars);
			$random_word      = '';
			while ($escape_char_plus < $repeat) {
				$random_word .= $chars[mt_rand(1, strlen($chars) - 1)];
				$escape_char_plus++;
			}

			return $random_word;
		}
	}